package com.cloudbench.util;



import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;




public class WebGet {

	
	public static WebNode GetWebValues() throws IOException{	
		Hashtable<Integer, Double> re_ht = new Hashtable<Integer, Double>();
		ArrayList<Integer> re_al = new ArrayList<Integer>();
		Log.d("st1", "st1");
		URL url = new URL("http://windmsb.appspot.com");
	URLConnection con = url.openConnection();
	Log.d("st2", "st2");
//	 BufferedReader br = new BufferedReader(
//             new InputStreamReader(con.getInputStream()));
//	BufferedInputStream bif = new BufferedInputStream(con.getInputStream());
	Log.d("st3", "st3");
	Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
	Log.d("st\4", "st4");
	Matcher m = p.matcher(con.getContentType());
	Log.d("st5.1", "st5.1");
	/* If Content-Type doesn't match this pre-conception, choose default and 
	 * hope for the best. */
	String charset = m.matches() ? m.group(1) : "ISO-8859-1";
	Log.d("st5.2", "st5.3");
	Reader r = new InputStreamReader(con.getInputStream(), charset);
	Log.d("st5", "st5");
	StringBuilder buf = new StringBuilder();
	//ObjectInputStream input = new ObjectInputStream(bif);
//	int avail = bif.available(); //bytes
	int avail = 0;
	System.out.println("Response content size incoming = " + avail + "bytes");
	while (true) {
	  int ch = r.read();
	  if (ch < 0)
	    break;
	  buf.append((char) ch);
	}
	String[] lines = buf.toString().split("\\n");
	for(String str: lines){
	    System.out.println("Content = " + str);
	    
	    if (str.contains("<blockquote>"))
	    {
	    	
	    	String[] ary = str.split(" ");
	    	for(int i = 0 ;i < ary.length -1 ; i++){
	    		if(ary[i].contains(";"))
	    		{
	    			String ID_AMOUNT[] = ary[i].split(";");
	    			System.out.println("ID " + ID_AMOUNT[0]);
	    			System.out.println("TASK " + ID_AMOUNT[1]);
	    			re_ht.put(Integer.parseInt(ID_AMOUNT[0]), Double.parseDouble(ID_AMOUNT[1]));
	    			re_al.add(Integer.parseInt(ID_AMOUNT[0]));
	    		}
	    		
	    		
	    	}
	    }
	}
	//Node nA=new Node(1,1);
	WebNode re_get = new WebNode(re_ht ,avail, re_al);
	return re_get;
	}
}



